package com.app.couponsharelife.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.appbar.AppBarLayout
import android.widget.OverScroller
import java.lang.reflect.Field


/**
 *Created by xct on 2018/12/22
 *Description:
 */
class MyBehavior(context: Context, attrs: AttributeSet): AppBarLayout.Behavior(context,attrs) {
    private val TAG = "CustomAppbarLayoutBehavior"
    private val TYPE_FLING = 1
    private var isFlinging: Boolean = false
    private var shouldBlockNestedScroll: Boolean = false
    override fun onInterceptTouchEvent(parent: CoordinatorLayout, child: AppBarLayout, ev: MotionEvent): Boolean {
        //LogUtil.d(TAG, "onInterceptTouchEvent:" + child.totalScrollRange)
        /*shouldBlockNestedScroll = false
        if (isFlinging) {
            shouldBlockNestedScroll = true
        }
        when (ev.actionMasked) {
            MotionEvent.ACTION_DOWN -> stopAppbarLayoutFling(child)  //手指触摸屏幕的时候停止fling事件
        }*/
        if (ev.actionMasked === ACTION_DOWN) {
            val scroller = getSuperSuperField(this, "scroller")
            if (scroller != null && scroller is OverScroller) {
                val overScroller = scroller as OverScroller?
                overScroller!!.abortAnimation()
            }
        }
        return super.onInterceptTouchEvent(parent, child, ev)
    }

    /**
     * 停止appbarLayout的fling事件
     * @param appBarLayout
     */
    private fun stopAppbarLayoutFling(appBarLayout: AppBarLayout) {
        //通过反射拿到HeaderBehavior中的flingRunnable变量
        try {
            val headerBehaviorType = this.javaClass.superclass!!.superclass
            val flingRunnableField = headerBehaviorType!!.getDeclaredField("flingRunnable")
            val scrollerField = headerBehaviorType.getDeclaredField("scroller")
            flingRunnableField.isAccessible = true
            scrollerField.isAccessible = true

            val flingRunnable = flingRunnableField.get(this) as Runnable
            val overScroller = scrollerField.get(this) as OverScroller
            if (flingRunnable != null) {
                //LogUtil.d(TAG, "存在flingRunnable")
                appBarLayout.removeCallbacks(flingRunnable)
                flingRunnableField.set(this, null)
            }
            if (overScroller != null && !overScroller.isFinished) {
                overScroller.abortAnimation()
            }
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }

    }

    private fun getSuperSuperField(paramClass: Any, paramString: String): Any? {
        var field: Field? = null
        var `object`: Any? = null
        try {
            field = paramClass.javaClass.superclass!!.superclass!!.getDeclaredField(paramString)
            field!!.isAccessible = true
            `object` = field!!.get(paramClass)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return `object`
    }
    override fun onStartNestedScroll(parent: CoordinatorLayout, child: AppBarLayout, directTargetChild: View, target: View, nestedScrollAxes: Int, type: Int): Boolean {
        //LogUtil.d(TAG, "onStartNestedScroll")
        stopAppbarLayoutFling(child)
        return super.onStartNestedScroll(parent, child, directTargetChild, target, nestedScrollAxes, type)
    }

    override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: AppBarLayout, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
        //LogUtil.d(TAG, "onNestedPreScroll:" + child.totalScrollRange + " ,dx:" + dx + " ,dy:" + dy + " ,type:" + type)

        //type返回1时，表示当前target处于非touch的滑动，
        //该bug的引起是因为appbar在滑动时，CoordinatorLayout内的实现NestedScrollingChild2接口的滑动子类还未结束其自身的fling
        //所以这里监听子类的非touch时的滑动，然后block掉滑动事件传递给AppBarLayout
        if (type == TYPE_FLING) {
            isFlinging = true
        }
        if (!shouldBlockNestedScroll) {
            super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type)
        }
    }

    override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: AppBarLayout, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) {
        /*LogUtil.d(TAG, "onNestedScroll: target:" + target.javaClass + " ," + child.totalScrollRange + " ,dxConsumed:"
                + dxConsumed + " ,dyConsumed:" + dyConsumed + " " + ",type:" + type)*/
        if (!shouldBlockNestedScroll) {
            super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
        }
    }

    override fun onStopNestedScroll(coordinatorLayout: CoordinatorLayout, abl: AppBarLayout, target: View, type: Int) {
        //LogUtil.d(TAG, "onStopNestedScroll")
        super.onStopNestedScroll(coordinatorLayout, abl, target, type)
        isFlinging = false
        shouldBlockNestedScroll = false
    }

}